import { Input, Modal } from "antd";
import MyButton from "../../MyButton";
import { request } from "../../../Api/api";
import { useState, useEffect, useCallback } from "react";
import { Table, Pagination } from "antd";

const SelectTestPaper = ({ open, onOk, onCancel }) => {
  const [data, setData] = useState([]);
  const [page, setPage] = useState({ current: 1, pageSize: 10 });
  const [where, setWhere] = useState({ searchWord: "" });
  const [total, setTotal] = useState(0);
  const columns = [
    { title: "名称", dataIndex: "name" },
    { title: "描述", dataIndex: "explain" },
    { title: "作者", dataIndex: "author" },
    {
      title: "考试时长",
      dataIndex: "examTime",
      render: (examTime) =>
        examTime.split(":")[0] + "小时" + examTime.split(":")[1] + "分钟",
    },
    { title: "总分", dataIndex: "sumPoint" },
    { title: "及格分", dataIndex: "passPoint" },
    {
      title: "创建时间",
      dataIndex: "createTime",
      render: (createTime) => new Date(createTime).toLocaleString(),
    },
    {
      title: "操作",
      dataIndex: "id",
      render: (_, { id, name }) => (
        <div>
          <MyButton type={"success"} onClick={() => onOk({ id, name })}>
            选择
          </MyButton>
        </div>
      ),
    },
  ];

  const bind = useCallback(async () => {
    const res = await request(
      "/testpaper/pagination",
      { page: page.current, limit: page.pageSize, key: where.searchWord },
      "GET"
    );
    if (res.code >= 0) {
      setTotal(res.data.total);
      setData(res.data.data);
    }
  }, [page, where]);
  useEffect(() => {
    async function fetchData() {
      await bind();
    }
    fetchData();
  }, [bind]);
  return (
    <Modal open={open} footer={null} onCancel={onCancel} width={"80%"}>
      <Input
        value={where.searchWord}
        onChange={(e) => setWhere({ searchWord: e.target.value })}
        placeholder="搜索"
      />

      <Table
        columns={columns}
        dataSource={data}
        pagination={false}
        rowKey={({ id }) => id}
        scroll={{ x: "max-content" }}
      />
      <Pagination
        total={total}
        current={page.current}
        pageSize={page.pageSize}
        onChange={(current, pageSize) => setPage({ current, pageSize })}
        showQuickJumper={true}
      />
    </Modal>
  );
};

export default SelectTestPaper;
